package com.ktjy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory;

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory=new org.apache.ibatis.session.SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException("初始化SqlSessionFactory失败");
        }
    }

    //创建并返回SqlSession实例
    public static SqlSession createSqlSession(){
        return factory.openSession(false);//关闭自动提交事务
    }

    //关闭SqlSession
    public static void closeSqlSession(SqlSession session){
        if(session!=null){
            session.close();
        }
    }
}
